package me.numark.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import me.numark.MainActivity;
import me.numark.R;
import me.numark.model.PushMessage;

/**
 * Created by ASUS on 2015/9/8.
 */
public class MessageBroadCastReceiver extends BroadcastReceiver{
    public static final String MESSAGE_ACTION = "me.numark.message";
    public static final String MESSAGE_OBJECT = "me.numark.object";
    public static final String HAS_NEW_MESSAGE = "has_new_message";
    NotificationManager notificationManager;
    public  PushMessage message;
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && !TextUtils.isEmpty(intent.getAction())
                && intent.getAction().equals(MESSAGE_ACTION)) {
            boolean hasNewMsg = intent.getBooleanExtra(HAS_NEW_MESSAGE,
                    false);
            if (hasNewMsg){
                message = (PushMessage) intent.getSerializableExtra(MESSAGE_OBJECT);
                Intent i = new Intent(context, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.mipmap.notification)
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
                        .setContentTitle(message.title)
                        .setContentText(message.description)
                        .setContentIntent(pendingIntent);
                if (notificationManager == null) {
                    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                }
                Notification build = nb.build();
                build.flags = Notification.FLAG_AUTO_CANCEL;
                notificationManager.notify(message.custom_content.uid, build);
            }

        }
    }

    public static void sendMessageBroadcast(Context context,
                                            boolean hasNewMessage,PushMessage msg) {
        Intent intent = new Intent(MessageBroadCastReceiver.MESSAGE_ACTION);
        intent.putExtra(MessageBroadCastReceiver.HAS_NEW_MESSAGE, hasNewMessage);
        Bundle bundle = new Bundle();
        bundle.putSerializable(MessageBroadCastReceiver.MESSAGE_OBJECT,msg);
        intent.putExtras(bundle);
        context.sendBroadcast(intent);
    }


}
